const router = require('koa-router')()
const { exec } = require('../db')
const jwt = require('jsonwebtoken')

router.prefix('/api')
// 注册
router.post('/register', async (ctx, next) => {
	const { phone, password } = ctx.request.body
	if (phone && password) {
		const data = await exec(
			`insert into weeks_users (phone, password) values (?, ?)`,
			[phone, password]
		)
		ctx.body = data
	} else {
		ctx.body = 'fail'
	}
})

// 登陆
router.post('/login', async (ctx, next) => {
	const { phone, password } = ctx.request.body
	const data = await exec(
		`select * from weeks_users where phone=? and password=?`,
		[phone, password]
	)
	const token = jwt.sign({ id: data[0].id, phone: data[0].phone }, '1904A', {
		expiresIn: '24h'
	})

	ctx.body = { token }
})

//
router.post('/routeItem', async (ctx, next) => {
	const { route_name, route_path } = ctx.request.body
	const data = await exec(
		`insert into weeks_routes (route_name, route_path) values (?, ?)`,
		[route_name, route_path]
	)
	ctx.body = { data }
})

router.get('/routeItem', async (ctx, next) => {
	const { page, size } = ctx.query
	let sql = ''
	if (page && size) {
		sql = `select * from weeks_routes limit ? offset ?`
	} else {
		sql = `select * from weeks_routes`
	}
	const data = await exec(sql, [size * 1, (page - 1) * size])
	ctx.body = { data }
})

// 编辑
router.put('/routeItem', async (ctx, next) => {
	const { route_name, route_path, id } = ctx.request.body
	console.log(route_name, route_path, id, '------------')
	const data = await exec(
		`update weeks_routes set route_name=?, route_path=? where id=?`,
		[route_name, route_path, id]
	)
	ctx.body = { data }
})

router.delete('/routeItem', async (ctx, next) => {
	const { id } = ctx.request.body
	const data = await exec(`delete from weeks_routes where id=?`, [id])
	ctx.body = { data }
})
// router.get('/', function (ctx, next) {
// 	ctx.body = 'this is a users response!'
// })

// router.get('/bar', function (ctx, next) {
// 	ctx.body = 'this is a users/bar response'
// })

module.exports = router
